package org.example.Page;

import lombok.SneakyThrows;
import org.example.POJO.online.MyMessage;
import org.example.POJO.online.Record;
import org.example.Utils.SocketUtil;
import org.example.Utils.UserFileManager;
import org.example.sever.ClientThread;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.net.Socket;

public class MyFrame extends JFrame implements ActionListener {

    private GamePanel gamePanel = null;

    private int camp;

    private String username;

    private Socket socket;

    private boolean isLocked = false;

    private String to;

    private ClientThread ct;

    private JTextField chatInput;

    private JTextArea chatDisplay;

    public JTextArea getChatDisplay() {
        return chatDisplay;
    }

    public void setChatDisplay(JTextArea chatDisplay) {
        this.chatDisplay = chatDisplay;
    }

    public void setLocked(boolean locked) {
        this.isLocked = locked;
        gamePanel.setLocked(isLocked);
    }

    public void setCamp(int camp) {
        this.camp = camp;
        gamePanel.setCurrentCamp(camp);
    }

    public void setUsername(String username) {
        this.username = username;
        gamePanel.setUsername(username);
    }

    public void setTo(String to) {
        this.to = to;
        gamePanel.setTo(to);
    }

    /*
                象棋主页设计
                * */
    public MyFrame(Socket socket, String username, String to) {
        this.socket = socket;
        this.username = username;
        this.to = to;

        setTitle(username);
        setSize(900, 630);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);

        // 创建左边容器（西）
        JPanel leftPanel = new JPanel();
        leftPanel.setLayout(new BoxLayout(leftPanel, BoxLayout.Y_AXIS));
        leftPanel.setBorder(BorderFactory.createTitledBorder("信息面板"));
        leftPanel.setPreferredSize(new Dimension((int) (getWidth() * 0.25), getHeight()));

        UserFileManager userFileManager = new UserFileManager();

        // 对手信息面板
        JPanel opponentInfoPanel = new JPanel(new BorderLayout());
        String opAvatar = userFileManager.getAvatar(to);
        ImageIcon opponentIcon = new ImageIcon(opAvatar);
        Image scaledOpponentImage = opponentIcon.getImage().getScaledInstance(100, 100, Image.SCALE_SMOOTH);

        // 创建一个面板来容纳头像、用户名以及新的文本显示框
        JPanel opponentDetailsPanel = new JPanel();
        opponentDetailsPanel.setLayout(new BorderLayout()); // 使用 BorderLayout 来组织元素

        // 添加文本显示框到详情面板 (放在头像上方)
        JLabel opponentStatusLabel = new JLabel("状态：在线", SwingConstants.CENTER);
        opponentDetailsPanel.add(opponentStatusLabel, BorderLayout.NORTH);

        // 添加头像到详情面板
        opponentDetailsPanel.add(new JLabel(new ImageIcon(scaledOpponentImage)), BorderLayout.CENTER);

        // 添加用户名标签到详情面板
        JLabel opponentNameLabel = new JLabel(to + " (对手)", SwingConstants.CENTER);
        opponentDetailsPanel.add(opponentNameLabel, BorderLayout.SOUTH);

        // 将详情面板添加到对手信息面板
        opponentInfoPanel.add(opponentDetailsPanel, BorderLayout.CENTER);
        opponentInfoPanel.setBorder(BorderFactory.createTitledBorder("对手信息"));
        leftPanel.add(opponentInfoPanel);

        // 自己的信息面板
        JPanel myInfoPanel = new JPanel(new BorderLayout());
        String avatar = userFileManager.getAvatar(username);
        ImageIcon myIcon = new ImageIcon(avatar); // 替换为实际路径
        Image scaledMyImage = myIcon.getImage().getScaledInstance(100, 100, Image.SCALE_SMOOTH);

        // 创建一个面板来容纳头像、用户名以及新的文本显示框
        JPanel myDetailsPanel = new JPanel();
        myDetailsPanel.setLayout(new BorderLayout()); // 使用 BorderLayout 来组织元素

        // 添加文本显示框到详情面板 (放在头像上方)
        JLabel myStatusLabel = new JLabel("状态：在线", SwingConstants.CENTER);
        myDetailsPanel.add(myStatusLabel, BorderLayout.NORTH);

        // 添加头像到详情面板
        myDetailsPanel.add(new JLabel(new ImageIcon(scaledMyImage)), BorderLayout.CENTER);

        // 添加用户名标签到详情面板
        JLabel myNameLabel = new JLabel(username + " (我)", SwingConstants.CENTER);
        myDetailsPanel.add(myNameLabel, BorderLayout.SOUTH);

        // 将详情面板添加到自己的信息面板
        myInfoPanel.add(myDetailsPanel, BorderLayout.CENTER);
        myInfoPanel.setBorder(BorderFactory.createTitledBorder("我的信息"));
        leftPanel.add(myInfoPanel);

        // 中间容器（中心），用于显示 GamePanel
        gamePanel = new GamePanel();
        gamePanel.setUsername(username);
        gamePanel.setSocket(socket);
        gamePanel.setTo(to);
        gamePanel.setMyFrame(this);
        gamePanel.startReceive();

        // 创建一个新的面板来容纳按钮，设置为水平排列
        JPanel buttonPanel = new JPanel(); // 默认是 FlowLayout
        buttonPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); // 添加一些内边距

        JLabel hintLabel = new JLabel("红方走");
        gamePanel.setHintLabel(hintLabel);
        buttonPanel.add(hintLabel);

        JButton backBtn = new JButton("悔棋");
        backBtn.setActionCommand("back");
        backBtn.addActionListener(this);
        backBtn.setPreferredSize(new Dimension(110, 60)); // 放大按钮大小
        buttonPanel.add(backBtn);

        JButton drawBtn = new JButton("求和");
        drawBtn.setActionCommand("peace");
        drawBtn.addActionListener(this);
        drawBtn.setPreferredSize(new Dimension(110, 60)); // 放大按钮大小
        buttonPanel.add(drawBtn);

        JButton giveUpBtn = new JButton("认输");
        giveUpBtn.setActionCommand("giveUp");
        giveUpBtn.addActionListener(this);
        giveUpBtn.setPreferredSize(new Dimension(110, 60)); // 放大按钮大小
        buttonPanel.add(giveUpBtn);

        // 创建一个新的面板来容纳 gamePanel 和 buttonPanel
        JPanel centerPanel = new JPanel(new BorderLayout());
        centerPanel.add(gamePanel, BorderLayout.CENTER); // 把 gamePanel 放在中间容器的中间位置
        centerPanel.add(buttonPanel, BorderLayout.SOUTH); // 把按钮移到中间容器的底部

        // 创建右边容器（东）
        JPanel rightPanel = new JPanel(new BorderLayout());
        rightPanel.setBorder(BorderFactory.createTitledBorder("聊天区"));

        // 增加右侧面板的宽度
        rightPanel.setPreferredSize(new Dimension((int) (getWidth() * 0.23), getHeight()));

        // 文本显示框
        chatDisplay = new JTextArea();
        chatDisplay.setEditable(false); // 设置为不可编辑
        chatDisplay.setLineWrap(true); // 自动换行
        chatDisplay.setWrapStyleWord(true); // 按单词换行
        JScrollPane scrollPane = new JScrollPane(chatDisplay);
        rightPanel.add(scrollPane, BorderLayout.CENTER);

        // 底部面板，用于放置文本输入框和发送按钮
        JPanel bottomPanelRight = new JPanel();
        bottomPanelRight.setLayout(new BorderLayout());

        chatInput = new JTextField();
        JButton sendButton = new JButton("发送");
        // 添加监听器到发送按钮
        sendButton.setActionCommand("send");
        sendButton.addActionListener(this);


        bottomPanelRight.add(chatInput, BorderLayout.CENTER);
        bottomPanelRight.add(sendButton, BorderLayout.EAST);

        rightPanel.add(bottomPanelRight, BorderLayout.SOUTH);

        // 使用 BorderLayout 来组织主框架中的组件
        setLayout(new BorderLayout());
        add(leftPanel, BorderLayout.WEST);
        add(centerPanel, BorderLayout.CENTER);
        add(rightPanel, BorderLayout.EAST);
        setVisible(true);
    }

    @SneakyThrows
    @Override
    public void actionPerformed(ActionEvent e) {
        String cmd = e.getActionCommand();
        switch (cmd) {
            case "back":
                MyMessage request = new MyMessage();
                request.setType(MyMessage.Type.BACK);
                request.setFrom(username);
                request.setTo(to);
                request.setContent(new Record());
                gamePanel.back(request);
                break;
            case "peace":
                peace();
                break;
            case "giveUp":
                giveUp();
                break;
            case "send":
                System.out.println("发送消息");
                send();
                default:
                break;
        }
    }

    //求和
    public void peace() {
        int result = JOptionPane.showConfirmDialog(null, "确认和对手求和", "求和", JOptionPane.YES_NO_OPTION);
        if (result == JOptionPane.YES_OPTION) {
            //发送求和请求消息
            MyMessage request = new MyMessage();
            request.setType(MyMessage.Type.PEACE);
            request.setFrom(username);
            request.setTo(to);
            request.setContent(new Record());
            try {
                SocketUtil.send(socket, request);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            //锁定棋盘
            gamePanel.setLocked(true);
            //求和按钮不能点击
        }
    }

    //认输
    public void giveUp() {
        int result = JOptionPane.showConfirmDialog(null, "确认认输", "认输", JOptionPane.YES_NO_OPTION);
        if (result == JOptionPane.YES_OPTION) {
            // 发送认输消息
            MyMessage request = new MyMessage();
            request.setType(MyMessage.Type.DEFEAT);
            request.setFrom(username);
            request.setTo(to);
            request.setContent(new Record());
            ct = gamePanel.getCt();
            try {
                SocketUtil.send(socket, request);
                this.dispose();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            ct.setShutdown(true);
            try {
                ct.join();
                ct.sleep(500);
                new GameLobby(socket, username);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }

        }
    }

    //发送信息
    public void send() {
        String content = chatInput.getText();
        if (content.isEmpty()) {
            JOptionPane.showMessageDialog(null, "请输入内容", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }
        MyMessage request = new MyMessage();
        request.setType(MyMessage.Type.CHAT);
        request.setFrom(username);
        request.setTo(to);
        request.setContent(content);
        try {
            SocketUtil.send(socket, request);
        }catch (IOException e){
            throw new RuntimeException(e);
        }
    }


}
